{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 协程\n",
    "- 参考资料\n",
    "    - python.jobbole.com/86481\n",
    "\n",
    "# 迭代器\n",
    "- 可迭代（Iterable）：直接作用于for循环的变量\n",
    "- 迭代器（Iterator）：不但可以作用于for循环，还可以被next调用\n",
    "- list是典型的可迭代对象，但是不是迭代器\n",
    "- 通过isinstance判断\n",
    "- iterable 和 iterator可以转换\n",
    "    - 通过iter函数\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "6\n",
      "7\n",
      "8\n",
      "9\n",
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "# 可迭代\n",
    "l = [ i for i in range(10)]\n",
    "\n",
    "# l是可迭代的对象，但不是迭代器\n",
    "for idx in l:\n",
    "    print(idx)\n",
    "\n",
    "# range(）是个迭代器\n",
    "for i in range(5):\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.7/site-packages/ipykernel_launcher.py:7: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working\n",
      "  import sys\n"
     ]
    }
   ],
   "source": [
    "# 判断是否可迭代\n",
    "from collections import Iterable\n",
    "ll = [1,2,3,4,5]\n",
    "\n",
    "print(isinstance(ll, Iterable))\n",
    "\n",
    "from collections import Iterator\n",
    "\n",
    "print(isinstance(ll, Iterator))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "# iter函数\n",
    "\n",
    "s = 'cheng ai fei'\n",
    "print(isinstance(s, Iterable))\n",
    "print(isinstance(s, Iterator))\n",
    "\n",
    "s_iter = iter(s)\n",
    "print(isinstance(s_iter, Iterable))\n",
    "print(isinstance(s_iter, Iterator))\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 生成器\n",
    "- generator：一边循环一边计算下一个元素的机制/算法\n",
    "- 需要满足：\n",
    "    - 每次调用都产生出for循环需要的下一个元素\n",
    "    - 如果达到最后一个后，爆出StopIteration异常\n",
    "    - 可以被next函数调用\n",
    "- 任何制作生成器\n",
    "    - 直接使用\n",
    "    - 如果函数中包含yield，则这个函数就叫生成器\n",
    "    - next调用函数，遇到yield返回"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'list'>\n",
      "<class 'generator'>\n"
     ]
    }
   ],
   "source": [
    "# 直接使用生成器\n",
    "L = [x*x for x in range(5)] # 放在中括号中是列表生成器\n",
    "g = (x*x for x in range(5)) # 放在小括号中就是生成器\n",
    "\n",
    "print(type(L))\n",
    "print(type(g))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step 1\n",
      "Step 2\n",
      "Step 3\n"
     ]
    }
   ],
   "source": [
    "# 函数案例\n",
    "def odd():\n",
    "    print('Step 1')\n",
    "    print('Step 2')\n",
    "    print('Step 3')\n",
    "    return None\n",
    "odd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step 1\n",
      "1\n",
      "Step 2\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "# 生成器案例\n",
    "def odd():\n",
    "    print('Step 1')\n",
    "    yield 1\n",
    "    print('Step 2')\n",
    "    yield 2\n",
    "    print('Step 3')\n",
    "    yield 2\n",
    "# odd()是调用生成器\n",
    "g = odd()\n",
    "one = next(g)\n",
    "print(one)\n",
    "two = next(g)\n",
    "print(two)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 协程\n",
    "- 3.4引入协程，用yield实现\n",
    "- 3.5引入协程语法\n",
    "    - 实现协程比较好的包有asyncio，tornado，gevent\n",
    "- 定义：协程是为非抢占式多任务产生子程序的计算机程序组件，协程允许不同入口点在不同位置暂停或开始执行程序\n",
    "- 从技术角度讲，协程就是一个你可以暂停执行的函数，或者干脆把协程理解成生成器\n",
    "- 协程的实现：\n",
    "    - yield返回\n",
    "    - send调用\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "111\n",
      "-> start\n",
      "222\n",
      "-> recived zhexiao\n"
     ]
    },
    {
     "ename": "StopIteration",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mStopIteration\u001b[0m                             Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-2-9bf8441729bb>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     13\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m222\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 14\u001b[0;31m \u001b[0msc\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'zhexiao'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mStopIteration\u001b[0m: "
     ]
    }
   ],
   "source": [
    "# 协程代码案例1\n",
    "def simple_coroutine():\n",
    "    print('-> start')\n",
    "    x = yield \n",
    "    print('-> recived', x)\n",
    "\n",
    "# 主线程\n",
    "sc = simple_coroutine()\n",
    "print(111)\n",
    "# 可以使用sc.send(None),效果一样\n",
    "next(sc) # 预激\n",
    "\n",
    "print(222)\n",
    "sc.send('zhexiao')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-> start\n",
      "5\n",
      "-> recived 5 6\n",
      "11\n",
      "->recived 5 6 7\n"
     ]
    },
    {
     "ename": "StopIteration",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mStopIteration\u001b[0m                             Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-4-32f465188441>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     13\u001b[0m \u001b[0mbb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msc\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m6\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     14\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 15\u001b[0;31m \u001b[0mcc\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msc\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m7\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     16\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcc\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mStopIteration\u001b[0m: "
     ]
    }
   ],
   "source": [
    "# 案例2，协程的状态\n",
    "\n",
    "def simple_coroutine(a):\n",
    "    print('-> start')\n",
    "    b = yield a\n",
    "    print('-> recived', a, b)\n",
    "    c = yield a + b\n",
    "    print('->recived', a, b, c)\n",
    "    \n",
    "sc = simple_coroutine(5)\n",
    "aa = next(sc)\n",
    "print(aa)\n",
    "bb = sc.send(6)\n",
    "print(bb)\n",
    "cc = sc.send(7)\n",
    "print(cc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 协程终止\n",
    "    - 协程中未处理的异常会向上冒泡，传给next函数或者send方法的调用方（即触法协程的对象）\n",
    "    - 终止协程的一种方式：发送某个哨符值，让协程退出。内置的None和Ellipsis等常量经常用作哨符值\n",
    "- yield from\n",
    "    - 调用协程为了得到返回值，协程必须正常终止\n",
    "    - 生成器正常终止会发出StopIteration异常，异常对象的value属性保存返回值\n",
    "    - yield from从内部捕获StopIteration异常\n",
    "    - 委派生成器\n",
    "        - 包含yield from表达式的生成器函数\n",
    "        - 委派生成器在yield from表达式处暂停，调用方可以直接把数据发给自生成器\n",
    "        - 子生成器再把产出的值发给调用方\n",
    "        - 自生成器在最后，解释会跑出StopIteration，并且把返回值附加到异常对象上\n",
    "     "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['A', 'B']\n",
      "['A', 'B']\n"
     ]
    }
   ],
   "source": [
    "# 案例3 yield from\n",
    "def gen():\n",
    "    for c in 'AB':\n",
    "        yield c\n",
    "        \n",
    "print(list(gen()))\n",
    "\n",
    "def gen_new():\n",
    "    yield from 'AB'\n",
    "print(list(gen_new()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# asyncio\n",
    "- pyhton3.4开始引入标准库当中，内置对异步io的支持\n",
    "- asyncio本身是一个消息循环\n",
    "- 步骤：\n",
    "    - 创建消息循环\n",
    "    - 把协程导入\n",
    "    - 关闭"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello world! (<_MainThread(MainThread, started 4364842432)>)\n",
      "Start..... (<_MainThread(MainThread, started 4364842432)>)\n",
      "Hello world! (<_MainThread(MainThread, started 4364842432)>)\n",
      "Start..... (<_MainThread(MainThread, started 4364842432)>)\n",
      "Done...... (<_MainThread(MainThread, started 4364842432)>)\n",
      "Hello again! (<_MainThread(MainThread, started 4364842432)>)\n",
      "Done...... (<_MainThread(MainThread, started 4364842432)>)\n",
      "Hello again! (<_MainThread(MainThread, started 4364842432)>)\n"
     ]
    }
   ],
   "source": [
    "import threading\n",
    "# 引入异步io包\n",
    "import asyncio\n",
    "\n",
    "# 使用协程\n",
    "@asyncio.coroutine\n",
    "def hello():\n",
    "    print('Hello world! (%s)' % threading.currentThread())\n",
    "    print('Start..... (%s)' % threading.currentThread())\n",
    "    yield from asyncio.sleep(10)\n",
    "    print('Done...... (%s)' % threading.currentThread())\n",
    "    print('Hello again! (%s)' % threading.currentThread())\n",
    "\n",
    "# 启动消息循环\n",
    "loop = asyncio.get_event_loop()\n",
    "# 定义任务\n",
    "tasks = [hello(), hello()]\n",
    "# asyncio使用wait等待tasks执行完毕\n",
    "loop.run_until_complete(asyncio.wait(tasks))\n",
    "loop.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# async和await\n",
    "- 为了更好的表示异步io\n",
    "- python3.5引入\n",
    "- 让协程代码更简洁\n",
    "- 使用上，可以简单替换：\n",
    "    - 用async替换@asyncio.coroutine\n",
    "    - 用await代替yield from"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# concurrent.futures\n",
    "- python3新增的库\n",
    "- 类似其他语言的线程池的概念\n",
    "- 利用multiprocessing实现真正的并行计算\n",
    "- 核心原理：并行运行多个python解释器，从而令python程序可以利用多核CPU来提升执行速度，由于子进程与主解释器相分离，所以他们的全局解释器锁也是相互独立的，每个子进程都能够完整的使用一个cpu内核。\n",
    "- concurrent.futures.Executor\n",
    "    - ThreadPoolExecutor\n",
    "    - ProcessPoolExecutor\n",
    "    - 执行的时候需要自行选择\n",
    "- submit(fn, args, kwargs)\n",
    "    - fn:异步执行的函数\n",
    "    - args，kwargs参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "hello\n",
      "world\n"
     ]
    }
   ],
   "source": [
    "# 关于concurrent的案例\n",
    "from concurrent.futures import ThreadPoolExecutor\n",
    "import time\n",
    "\n",
    "def return_future(msg):\n",
    "    time.sleep(3)\n",
    "    return msg\n",
    "\n",
    "# 创建一个线程池\n",
    "pool = ThreadPoolExecutor(max_workers=2)\n",
    "\n",
    "# 往线程池加入2个task\n",
    "f1 = pool.submit(return_future, 'hello')\n",
    "f2 = pool.submit(return_future, 'world')\n",
    "\n",
    "# done等待执行完毕\n",
    "print(f1.done())\n",
    "time.sleep(3)\n",
    "print(f2.done())\n",
    "\n",
    "# result等待结果\n",
    "print(f1.result())\n",
    "print(f2.result())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
